package com.xiaoma.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * ServerSocketChannel:在服务器端监听新的客户端Socket连接，并产生一个SocketChannel
 * SocketChannel：网络IO通道，具体负责的读写操作
 */
public class NIOServer {
    public static void main(String[] args) throws Exception {
        //ServerSocketChannel -> ServerSocket 服务端的连接
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //创建一个Selector对象
        Selector selector = Selector.open();
        //绑定一个端口6666，在服务器端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //把ServerSocketChannel注册到Selector 关心事件为 OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
       //循环等待客户端连接
        while (true){
            if (selector.select(1000)==0){
                System.out.println("服务器等待了1S，无连接");
                continue;
            }
            //获取到关注事件集合并遍历
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //根据key对应 通道发生的事件做相应处理
                if (key.isAcceptable()){ // 如果是OP_ACCEPT，有新的客户端连接
                    //生成一个SocketChannel -> Socket  客户端的连接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    //设置为非阻塞
                    socketChannel.configureBlocking(false);
                    System.out.println("客户端连接成功"+socketChannel.hashCode());
                    //将SocketChannel注册到Selector 关注事件为OP_READ，同时关联一个Buffer
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()){// 如果是OP_READ
                    //通过key获取到当前SocketChannel 客户端
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到关联的Buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("读取到了数据："+new String(buffer.array()));
                }
                //操作完成 移除当前key
                iterator.remove();
            }
        }
    }
}
